package com.suixun.controller.handle;

import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.suixun.enums.ApiCode;
import com.suixun.exceptions.SuixunException;
import com.suixun.result.Result;
import com.suixun.utils.JsonUtils;

/**
 * 功能描述: 异常拦截器
 * 
 * @author jacky
 * @date 2018年1月5日下午7:12:22
 */
@Component
public class ExceptionHandle extends SimpleMappingExceptionResolver {

	private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		String requestURI = request.getRequestURI();
		Map<String, String[]> params = request.getParameterMap();
		String queryString = "";
		if (params != null)
			queryString = params.size() + " params->";
		try {
			for (String key : params.keySet()) {
				String[] values = params.get(key);
				for (int i = 0; i < values.length; i++) {
					String value = values[i];
					queryString += key + "=" + value + "&";
				}
			}
		} catch (Exception e) {

		}

		try {
			response.setContentType(MediaType.APPLICATION_JSON_VALUE);
			response.setCharacterEncoding("utf-8");
			ServletOutputStream out = response.getOutputStream();
			String json = null;
			response.setStatus(ApiCode.HTTP_200.getCode());
			// 针对SuixunException
			if (ex instanceof SuixunException) {
				SuixunException suixunException = (SuixunException) ex;
				Result result = null;
				if (suixunException.getApiCode() != null) {
					result = new Result(suixunException.getApiCode(), null);
				} else {
					result = new Result(ApiCode.HTTP_500.setCustomMsg(suixunException.getMsg()), null);
				}
				json = JsonUtils.toJson(result);
			} else {
				Result result = new Result(ApiCode.HTTP__500, null);
				json = JsonUtils.toJson(result);
				if (logger.isErrorEnabled()) {
					logger.error("suixunException: " + ex.getMessage() + ",requestUrl： " + requestURI + "callPath: "
							+ queryString, ex);
				}
			}
			out.write(json.getBytes());
			out.close();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}
}
